Full Code of olahol/go-imageupload for AI

master 9b3f98f8b737 cached
13 files
8.9 KB
2.8k tokens
14 symbols
1 requests
Download .txt
Repository: olahol/go-imageupload
Branch: master
Commit: 9b3f98f8b737
Files: 13
Total size: 8.9 KB

Directory structure:
gitextract_lsq4_nwm/

├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── examples/
│   ├── save/
│   │   ├── index.html
│   │   └── main.go
│   ├── simple/
│   │   ├── index.html
│   │   └── main.go
│   └── thumbnailer/
│       ├── index.html
│       └── main.go
├── go.mod
├── go.sum
└── imageupload.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
.DS_Store
*.swp


================================================
FILE: CHANGELOG.md
================================================
# 2022-09-14 (v1.0.0)

* Create Go module.

# 2016-05-03

* Add the PNG/JPEG thumbnail methods to *Image.


================================================
FILE: LICENSE
================================================
Copyright (c) 2022. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

  Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


================================================
FILE: README.md
================================================
# go-imageupload

[![GoDoc](https://godoc.org/github.com/olahol/go-imageupload?status.svg)](https://godoc.org/github.com/olahol/go-imageupload)

> :white_square_button: Gracefully handle image uploading and thumbnail creation.

## Install

```bash
go get github.com/olahol/go-imageupload
```

## [Example](https://github.com/olahol/go-imageupload/tree/master/examples)

Thumbnail creator.

```go
package main

import (
	"net/http"

	"github.com/olahol/go-imageupload"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.NotFound(w, r)
			return
		}

		img, err := imageupload.Process(r, "file")

		if err != nil {
			panic(err)
		}

		thumb, err := imageupload.ThumbnailPNG(img, 300, 300)

		if err != nil {
			panic(err)
		}

		thumb.Write(w)
	})

	http.ListenAndServe(":5000", nil)
}
```

```html
<html>
<body>
  <form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
  </form>
</body>
</html>
```

## Contributors

* Ola Holmström (@olahol)
* Shintaro Kaneko (@kaneshin)


## [Documentation](https://godoc.org/github.com/olahol/go-imageupload)


================================================
FILE: examples/save/index.html
================================================
<!DOCTYPE html>
<html>
<body>
  <form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
  </form>
</body>
</html>


================================================
FILE: examples/save/main.go
================================================
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/olahol/go-imageupload"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.NotFound(w, r)
			return
		}

		img, err := imageupload.Process(r, "file")

		if err != nil {
			panic(err)
		}

		thumb, err := imageupload.ThumbnailPNG(img, 300, 300)

		if err != nil {
			panic(err)
		}

		thumb.Save(fmt.Sprintf("%d.png", time.Now().Unix()))

		http.Redirect(w, r, "/", http.StatusMovedPermanently)
	})

	http.ListenAndServe(":5000", nil)
}


================================================
FILE: examples/simple/index.html
================================================
<!DOCTYPE html>
<html>
<body>
  <form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
  </form>

  <a href="/image"><img src="/thumbnail"></a>
</body>
</html>


================================================
FILE: examples/simple/main.go
================================================
package main

import (
	"net/http"

	"github.com/olahol/go-imageupload"
)

var currentImage *imageupload.Image

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	http.HandleFunc("/image", func(w http.ResponseWriter, r *http.Request) {
		if currentImage == nil {
			http.NotFound(w, r)
			return
		}

		currentImage.Write(w)
	})

	http.HandleFunc("/thumbnail", func(w http.ResponseWriter, r *http.Request) {
		if currentImage == nil {
			http.NotFound(w, r)
			return
		}

		t, err := imageupload.ThumbnailJPEG(currentImage, 300, 300, 80)

		if err != nil {
			panic(err)
		}

		t.Write(w)
	})

	http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.NotFound(w, r)
			return
		}

		img, err := imageupload.Process(r, "file")

		if err != nil {
			panic(err)
		}

		currentImage = img

		http.Redirect(w, r, "/", http.StatusMovedPermanently)
	})

	http.ListenAndServe(":5000", nil)
}


================================================
FILE: examples/thumbnailer/index.html
================================================
<html>
<body>
  <form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
  </form>
</body>
</html>


================================================
FILE: examples/thumbnailer/main.go
================================================
package main

import (
	"net/http"

	"github.com/olahol/go-imageupload"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.NotFound(w, r)
			return
		}

		img, err := imageupload.Process(r, "file")

		if err != nil {
			panic(err)
		}

		thumb, err := imageupload.ThumbnailPNG(img, 300, 300)

		if err != nil {
			panic(err)
		}

		thumb.Write(w)
	})

	http.ListenAndServe(":5000", nil)
}


================================================
FILE: go.mod
================================================
module github.com/olahol/go-imageupload

go 1.19

require github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646


================================================
FILE: go.sum
================================================
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=


================================================
FILE: imageupload.go
================================================
// Gracefully handle image uploading and thumbnail creation.
package imageupload

import (
	"bytes"
	"encoding/base64"
	"errors"
	"fmt"
	"github.com/nfnt/resize"
	"image"
	_ "image/gif"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"net/http"
	"strconv"
)

type Image struct {
	Filename    string
	ContentType string
	Data        []byte
	Size        int
}

// Save image to file.
func (i *Image) Save(filename string) error {
	return ioutil.WriteFile(filename, i.Data, 0600)
}

// Convert image to base64 data uri.
func (i *Image) DataURI() string {
	return fmt.Sprintf("data:%s;base64,%s", i.ContentType, base64.StdEncoding.EncodeToString(i.Data))
}

// Write image to HTTP response.
func (i *Image) Write(w http.ResponseWriter) {
	w.Header().Set("Content-Type", i.ContentType)
	w.Header().Set("Content-Length", strconv.Itoa(i.Size))
	w.Write(i.Data)
}

// Create JPEG thumbnail from image.
func (i *Image) ThumbnailJPEG(width int, height int, quality int) (*Image, error) {
	return ThumbnailJPEG(i, width, height, quality)
}

// Create PNG thumbnail from image.
func (i *Image) ThumbnailPNG(width int, height int) (*Image, error) {
	return ThumbnailPNG(i, width, height)
}

// Limit the size of uploaded files, put this before imageupload.Process.
func LimitFileSize(maxSize int64, w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, maxSize)
}

func okContentType(contentType string) bool {
	return contentType == "image/png" || contentType == "image/jpeg" || contentType == "image/gif"
}

// Process uploaded file into an image.
func Process(r *http.Request, field string) (*Image, error) {
	file, info, err := r.FormFile(field)

	if err != nil {
		return nil, err
	}

	contentType := info.Header.Get("Content-Type")

	if !okContentType(contentType) {
		return nil, errors.New(fmt.Sprintf("Wrong content type: %s", contentType))
	}

	bs, err := ioutil.ReadAll(file)

	if err != nil {
		return nil, err
	}

	_, _, err = image.Decode(bytes.NewReader(bs))

	if err != nil {
		return nil, err
	}

	i := &Image{
		Filename:    info.Filename,
		ContentType: contentType,
		Data:        bs,
		Size:        len(bs),
	}

	return i, nil
}

// Create JPEG thumbnail.
func ThumbnailJPEG(i *Image, width int, height int, quality int) (*Image, error) {
	img, _, err := image.Decode(bytes.NewReader(i.Data))

	thumbnail := resize.Thumbnail(uint(width), uint(height), img, resize.Lanczos3)

	data := new(bytes.Buffer)
	err = jpeg.Encode(data, thumbnail, &jpeg.Options{
		Quality: quality,
	})

	if err != nil {
		return nil, err
	}

	bs := data.Bytes()

	t := &Image{
		Filename:    "thumbnail.jpg",
		ContentType: "image/jpeg",
		Data:        bs,
		Size:        len(bs),
	}

	return t, nil
}

// Create PNG thumbnail.
func ThumbnailPNG(i *Image, width int, height int) (*Image, error) {
	img, _, err := image.Decode(bytes.NewReader(i.Data))

	thumbnail := resize.Thumbnail(uint(width), uint(height), img, resize.Lanczos3)

	data := new(bytes.Buffer)
	err = png.Encode(data, thumbnail)

	if err != nil {
		return nil, err
	}

	bs := data.Bytes()

	t := &Image{
		Filename:    "thumbnail.png",
		ContentType: "image/png",
		Data:        bs,
		Size:        len(bs),
	}

	return t, nil
}
Download .txt
gitextract_lsq4_nwm/

├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── examples/
│   ├── save/
│   │   ├── index.html
│   │   └── main.go
│   ├── simple/
│   │   ├── index.html
│   │   └── main.go
│   └── thumbnailer/
│       ├── index.html
│       └── main.go
├── go.mod
├── go.sum
└── imageupload.go
Download .txt
SYMBOL INDEX (14 symbols across 4 files)

FILE: examples/save/main.go
  function main (line 11) | func main() {

FILE: examples/simple/main.go
  function main (line 11) | func main() {

FILE: examples/thumbnailer/main.go
  function main (line 9) | func main() {

FILE: imageupload.go
  type Image (line 19) | type Image struct
    method Save (line 27) | func (i *Image) Save(filename string) error {
    method DataURI (line 32) | func (i *Image) DataURI() string {
    method Write (line 37) | func (i *Image) Write(w http.ResponseWriter) {
    method ThumbnailJPEG (line 44) | func (i *Image) ThumbnailJPEG(width int, height int, quality int) (*Im...
    method ThumbnailPNG (line 49) | func (i *Image) ThumbnailPNG(width int, height int) (*Image, error) {
  function LimitFileSize (line 54) | func LimitFileSize(maxSize int64, w http.ResponseWriter, r *http.Request) {
  function okContentType (line 58) | func okContentType(contentType string) bool {
  function Process (line 63) | func Process(r *http.Request, field string) (*Image, error) {
  function ThumbnailJPEG (line 99) | func ThumbnailJPEG(i *Image, width int, height int, quality int) (*Image...
  function ThumbnailPNG (line 126) | func ThumbnailPNG(i *Image, width int, height int) (*Image, error) {
Condensed preview — 13 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (11K chars).
[
  {
    "path": ".gitignore",
    "chars": 16,
    "preview": ".DS_Store\n*.swp\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 106,
    "preview": "# 2022-09-14 (v1.0.0)\n\n* Create Go module.\n\n# 2016-05-03\n\n* Add the PNG/JPEG thumbnail methods to *Image.\n"
  },
  {
    "path": "LICENSE",
    "chars": 1282,
    "preview": "Copyright (c) 2022. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodificatio"
  },
  {
    "path": "README.md",
    "chars": 1307,
    "preview": "# go-imageupload\n\n[![GoDoc](https://godoc.org/github.com/olahol/go-imageupload?status.svg)](https://godoc.org/github.com"
  },
  {
    "path": "examples/save/index.html",
    "chars": 188,
    "preview": "<!DOCTYPE html>\n<html>\n<body>\n  <form method=\"POST\" action=\"/upload\" enctype=\"multipart/form-data\">\n    <input type=\"fil"
  },
  {
    "path": "examples/save/main.go",
    "chars": 685,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/olahol/go-imageupload\"\n)\n\nfunc main() {\n\thttp.HandleFunc"
  },
  {
    "path": "examples/simple/index.html",
    "chars": 235,
    "preview": "<!DOCTYPE html>\n<html>\n<body>\n  <form method=\"POST\" action=\"/upload\" enctype=\"multipart/form-data\">\n    <input type=\"fil"
  },
  {
    "path": "examples/simple/main.go",
    "chars": 1012,
    "preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/olahol/go-imageupload\"\n)\n\nvar currentImage *imageupload.Image\n\nfunc mai"
  },
  {
    "path": "examples/thumbnailer/index.html",
    "chars": 172,
    "preview": "<html>\n<body>\n  <form method=\"POST\" action=\"/upload\" enctype=\"multipart/form-data\">\n    <input type=\"file\" name=\"file\">\n"
  },
  {
    "path": "examples/thumbnailer/main.go",
    "chars": 575,
    "preview": "package main\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/olahol/go-imageupload\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"/\", func(w ht"
  },
  {
    "path": "go.mod",
    "chars": 116,
    "preview": "module github.com/olahol/go-imageupload\n\ngo 1.19\n\nrequire github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646\n"
  },
  {
    "path": "go.sum",
    "chars": 219,
    "preview": "github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=\ngithub.com/nfn"
  },
  {
    "path": "imageupload.go",
    "chars": 3199,
    "preview": "// Gracefully handle image uploading and thumbnail creation.\npackage imageupload\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t"
  }
]

About this extraction

This page contains the full source code of the olahol/go-imageupload GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 13 files (8.9 KB), approximately 2.8k tokens, and a symbol index with 14 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!