This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Rest api to upload images in Go


On this article we’re going to study how we are able to create a relaxation api to add picture, we’ll additionally going to be sure that our api will deal with a number of picture add as nicely and we’re additionally going to set the file add restrict so it will not make our system unstable, as a result of lengthy file add may cause the system failure difficulty so it is higher so as to add a restrict for the file, and we’re going to be sure that we solely settle for picture so we additionally want so as to add file sort checking as nicely for our api, in order for you pictures and docs from the identical api you may take away the kind checking filter and api is able to deal with a number of sort information.

Steps we have to observe to make our relaxation api to add pictures.

  • Create Repostory.
  • Setup go.mod.
  • Create fundamental.go file
  • Setup http server utilizing gorilla mux package deal.
  • Create the api.
  • Join the remaining api with http handler.
  • Check the api.

Let’s observe the steps one after the other to create the successfull relaxation api to add pictures.



1. Create Repository

First we have to create the folder the place we are able to setup our codebase.
Create a folder referred to as upload-images-rest-api. beneath is the command to create listing/folder.

$ mkdir add-pictures-relaxation-api
Enter fullscreen mode

Exit fullscreen mode



2. Setup go.mod

We additionally have to setup go.mod file in upload-images-rest-api folder, so we are able to use our code as package deal/module, beneath is the command to generate the go.mod file.

$ go mod init add-pictures-relaxation-api
Enter fullscreen mode

Exit fullscreen mode

In case you are new to Go you then may want to know the go packaging first to know what this command do.



3. Create fundamental.go file

Inside your upload-images-rest-api folder create one other file referred to as fundamental.go

$ contact fundamental.go
Enter fullscreen mode

Exit fullscreen mode

as now now we have additionally created our fundamental.go file now we are able to begin improvement of our http server.



4. Setup http server utilizing gorilla mux package deal

For creating server we’re going to use gorilla mux package deal so first we have to obtain the package deal first then we are able to begin the event.

Beneath is the command to obtain the gorilla mux package deal

$ go get -u github.com/gorilla/mux 
Enter fullscreen mode

Exit fullscreen mode

After the set up of gorilla mux we are able to begin the event of our code.



1. Create fundamental operate.

First we have to write the boiler plate code of Go, beneath is the code

package deal fundamental

func fundamental() {

}
Enter fullscreen mode

Exit fullscreen mode

As of now it is a boiler plate code that is why we have no package deal loaded but.



2. Create HTTP Server.

Beneath is the code of the http server.

package deal fundamental

import (
    "log"
    "internet/http"

    "github.com/gorilla/mux"
)

const PORT = "8080"

func fundamental() {
    r := mux.NewRouter()
    r.HandleFunc("/ping", nil).Strategies("GET")
    r.HandleFunc("/add", nil).Strategies("POST")

    log.Printf("Server is working on http://localhost:%s", PORT)
    log.Println(http.ListenAndServe(":"+PORT, r))
}
Enter fullscreen mode

Exit fullscreen mode

First we added the PORT variable through which we would like our server to run which is 8080, Inside the primary operate now we have referred to as the mux.NewRouter operate of our gorilla mux package deal after which now we have created our routes as talked about within the code and in addition hooked up their strategies as nicely, as you may see now we have two API, first /pingis to examine if our server is alive or not and second /add is for our fundamental work to add pictures, then we’re passing our mux router to http.ListenAndServe operate and in addition passing the port on we would like our server to run.

In the event you attempt to run the server and go to check any of the api you will get the error like this as a result of we simply handed the trail however for the offered path their is not any handler which might learn that deal with that request.

2022/11/27 19:16:00 http: panic serving [::1]:56663: runtime error: invalid reminiscence tackle or nil pointer dereference
goroutine 18 [running]:
internet/http.(*conn).serve.func1()
        C:/Program Recordsdata/Go/src/internet/http/server.go:1850 +0xbf
panic({0xe08000, 0x1025de0})
        C:/Program Recordsdata/Go/src/runtime/panic.go:890 +0x262
internet/http.HandlerFunc.ServeHTTP(0xc000148000?, {0xebd248?, 0xc0001360e0?}, 0x800?)
        C:/Program Recordsdata/Go/src/internet/http/server.go:2109 +0x1e
github.com/gorilla/mux.(*Router).ServeHTTP(0xc000130000, {0xebd248, 0xc0001360e0}, 0xc000096100)
        C:/Customers/KDSINGH/go/pkg/mod/github.com/gorilla/mux@v1.8.0/mux.go:210 +0x1cf
internet/http.serverHandler.ServeHTTP({0xc000088120?}, {0xebd248, 0xc0001360e0}, 0xc000096100)
        C:/Program Recordsdata/Go/src/internet/http/server.go:2947 +0x30c
internet/http.(*conn).serve(0xc00009e000, {0xebd680, 0xc000073320})
        C:/Program Recordsdata/Go/src/internet/http/server.go:1991 +0x607
created by internet/http.(*Server).Serve
        C:/Program Recordsdata/Go/src/internet/http/server.go:3102 +0x4db

Enter fullscreen mode

Exit fullscreen mode

To unravel this difficulty let’s create our a http handler for our /ping api which will probably be used as a api heartbeat to examine if server is working or not.

Let’s add the handler for the /ping route:

func Ping(w http.ResponseWriter, r *http.Request) {
    reply := map[string]interface{}{
        "messageType": "S",
        "message":     "",
        "knowledge":        "PONG",
    }
    w.Header().Set("Content material-Sort", "utility/json")
    w.WriteHeader(200)
    json.NewEncoder(w).Encode(reply)
}
Enter fullscreen mode

Exit fullscreen mode

We now have added the Ping operate to deal with the /ping route and contained in the Ping operate now we have added our response construction as map[string]interface so we are able to add dynamic response as we would like, we’re not depending on struct. We now have added messageType, message and knowledge as our response we going to make use of the identical response json for our /add api anticipate that knowledge will probably be going to a struct with a number of fields.

In subsequent we’re write our header content material sort and http code after which encoding and immediately returning again our response as json.



3. Add Ping operate into handler

Now now we have our Pingoperate let’s add this in our /ping handler.

r.HandleFunc("/ping", Ping).Strategies("GET")
Enter fullscreen mode

Exit fullscreen mode

Now now we have added our Ping handler as nicely, Let’s take a look at the API.
You may take a look at the api utilizing postman or your browser as ping does not accepts any parameter so it may be take a look at on browser as nicely.

Postman
postman

Browser
browser

/ping is working as anticipated, now it is time to implement our fundamental handler as nicely.



4. Create the api to add pictures

Beneath is the complete code of add picture relaxation api

// handler to deal with the picture add
func UploadImages(w http.ResponseWriter, r *http.Request) {
    // 32 MB is the default utilized by FormFile() operate
    if err := r.ParseMultipartForm(BULK_FILE_SIZE); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // Get a reference to the fileHeaders.
    // They're accessible solely after ParseMultipartForm is named
    information := r.MultipartForm.File["file"]

    var errNew string
    var http_status int

    for _, fileHeader := vary information {
        // Open the file
        file, err := fileHeader.Open()
        if err != nil {
            errNew = err.Error()
            http_status = http.StatusInternalServerError
            break
        }

        defer file.Shut()

        buff := make([]byte, 512)
        _, err = file.Learn(buff)
        if err != nil {
            errNew = err.Error()
            http_status = http.StatusInternalServerError
            break
        }

        // checking the content material sort
        // so we do not permit information apart from pictures
        filetype := http.DetectContentType(buff)
        if filetype != "picture/jpeg" && filetype != "picture/png" && filetype != "picture/jpg" {
            errNew = "The offered file format will not be allowed. Please add a JPEG,JPG or PNG picture"
            http_status = http.StatusBadRequest
            break
        }

        _, err = file.Search(0, io.SeekStart)
        if err != nil {
            errNew = err.Error()
            http_status = http.StatusInternalServerError
            break
        }

        err = os.MkdirAll("./uploads", os.ModePerm)
        if err != nil {
            errNew = err.Error()
            http_status = http.StatusInternalServerError
            break
        }

        f, err := os.Create(fmt.Sprintf("./uploads/%dpercents", time.Now().UnixNano(), filepath.Ext(fileHeader.Filename)))
        if err != nil {
            errNew = err.Error()
            http_status = http.StatusBadRequest
            break
        }

        defer f.Shut()

        _, err = io.Copy(f, file)
        if err != nil {
            errNew = err.Error()
            http_status = http.StatusBadRequest
            break
        }
    }
    message := "file uploaded efficiently"
    messageType := "S"

    if errNew != "" {
        message = errNew
        messageType = "E"
    }

    if http_status == 0 {
        http_status = http.StatusOK
    }

    resp := map[string]interface{}{
        "messageType": messageType,
        "message":     message,
    }
    w.Header().Set("Content material-Sort", "utility/json")
    w.WriteHeader(http_status)
    json.NewEncoder(w).Encode(resp)
}
Enter fullscreen mode

Exit fullscreen mode

We now have added our new handler UploadImages and added the examine for restricted dimension knowledge add for our /add endpoint, we’re passing the BULK_FILE_SIZE into r.ParseMultipartForm operate.

In subsequent step we’re getting the all uploaded file utilizing r.MultipartForm.File["file"] and it is giving us the map[string][]*multipart.FileHeader on which we’re iterating our loop sequentially.

Contained in the loop first we’re opening the file utilizing fileHeader.Open() and processing the returned info file, subsequent we’re studying the opened file info in chunks buff := make([]byte, 512) utilizing file.Learn(buff) operate: we’re passing our opened file to Learn methodology and in addition passing the bytes we have to learn from the opened file.

After studying small chunk from file we’re passing that chunks http.DetectContentType operate and it is returning again the file sort and in subsequent step we’re checking file sort, we’re solely accepting JPEG, JPG and PNG pictures.

In subsequent step we’re calling file.Search(0, io.SeekStart) for searching for picture knowledge fron given offset to whence, then we’re creating the uploads folder within the root degree of the undertaking, after creating folder we’re creating the file the place we are able to save the picture knowledge now we have opened, and in subsequent we’re calling io.Copy(f, file) and passing the information file into our newly created file f.

Ultimately of the operate we’re simply processing the request and we want if the operate acquired any error processing the picture then it will return the error in any other case it will return again the successfull message as sort json response.



5. Join the remaining api with http handler

Now now we have our handler for /add api however it’s not linked but so let’s join it after which we’ll take a look at our code, We simply want so as to add the UploadImages operate as second argument into our /add handlefunc.

r.HandleFunc("/add", UploadImages).Strategies("POST")
Enter fullscreen mode

Exit fullscreen mode



6. Check the API.

We now have linked our handlers with our routers, It is time to take a look at the /add route:

upload image

file-uploaded

This text is initially posted on programmingeeksclub.com

My Private Running a blog Web site : Programming Geeks Club
My Fb Web page : Programming Geeks Club
My Telegram Channel : Programming Geeks Club
My Twitter Account : Kuldeep Singh
My Youtube Channel: Programming Geeks Club



The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?