Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set http.ResponseWriter Content-Type header globally for all API endpoints?

I am new to Go and I'm building a simple API with it now:

package main  import (     "encoding/json"     "fmt"     "github.com/gorilla/mux"     "github.com/gorilla/handlers"     "log"     "net/http" )  func main() {     port := ":3000"     var router = mux.NewRouter()     router.HandleFunc("/m/{msg}", handleMessage).Methods("GET")     router.HandleFunc("/n/{num}", handleNumber).Methods("GET")      headersOk := handlers.AllowedHeaders([]string{"Authorization"})     originsOk := handlers.AllowedOrigins([]string{"*"})     methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})      fmt.Printf("Server is running at http://localhost%s\n", port)     log.Fatal(http.ListenAndServe(port, handlers.CORS(originsOk, headersOk, methodsOk)(router))) }  func handleMessage(w http.ResponseWriter, r *http.Request) {     vars := mux.Vars(r)     message := vars["msg"]     response := map[string]string{"message": message}     w.Header().Set("Content-Type", "application/json") // this     json.NewEncoder(w).Encode(response) }  func handleNumber(w http.ResponseWriter, r *http.Request) {     vars := mux.Vars(r)     number := vars["num"]     response := map[string]string{"number": number}     w.Header().Set("Content-Type", "application/json") // and this     json.NewEncoder(w).Encode(response) } 

I feel like it's not clean to keep repeating w.Header().Set("Content-Type", "application/json") line in every API function that I have.

So my question here is, does it possible to set that http.ResponseWriter Content-Type header globally for all API functions that I have?

like image 718
Zulhilmi Zainudin Avatar asked Jul 21 '18 12:07

Zulhilmi Zainudin


People also ask

What is Content-Type header in API?

The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc. In response, it tells about the type of returned content, to the client.

What is default Content-Type HTTP?

The default content type is usually “application/octet-stream” with the most generic MIME/type definition. The MIME/type is appropriate for any content type a web server is likely to serve.

What is headers Content-Type application JSON?

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html. Keep in mind, that JSON in JavaScript is an array or object.


1 Answers

You can define middleware for mux router, here is an example:

func main() {     port := ":3000"     var router = mux.NewRouter()     router.Use(commonMiddleware)      router.HandleFunc("/m/{msg}", handleMessage).Methods("GET")     router.HandleFunc("/n/{num}", handleNumber).Methods("GET")     // rest of code goes here }  func commonMiddleware(next http.Handler) http.Handler {     return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {         w.Header().Add("Content-Type", "application/json")         next.ServeHTTP(w, r)     }) } 

Read more in the documentation

like image 59
Philidor Avatar answered Oct 01 '22 09:10

Philidor