Http Server Golang

[Solved] Http Server Golang | Erlang - Code Explorer | yomemimo.com
Question : go http server example

Answered by : restu-wahyu-saputra

package main
import (	"encoding/json"	"fmt"	"log"	"net/http"
)
type Response struct {	Message string `json:"message"`
}
func GetRequest(rw http.ResponseWriter, req *http.Request) {	rw.Header().Add("Content-Type", "application/json")	if req.Method == "GET" {	data := Response{Message: "Hello World From - GET"}	json, _ := json.Marshal(data)	fmt.Fprint(rw, string(json))	} else {	data := Response{Message: "Bad Request"}	json, _ := json.Marshal(data)	fmt.Fprint(rw, string(json))	}
}
func PostRequest(rw http.ResponseWriter, req *http.Request) {	rw.Header().Add("Content-Type", "application/json")	if req.Method == "POST" {	data := Response{Message: "Hello World From - POST"}	json, _ := json.Marshal(data)	fmt.Fprint(rw, string(json))	} else {	data := Response{Message: "Bad Request"}	json, _ := json.Marshal(data)	fmt.Fprint(rw, string(json))	}
}
func main() {	http.HandleFunc("/get", GetRequest)	http.HandleFunc("/post", PostRequest)	log.Fatal(http.ListenAndServe(":8000", nil))
}

Source : | Last Update : Wed, 13 Oct 21

Question : golang http server

Answered by : restu-wahyu-saputra

type ApiResponse struct {	Code uint32	Message string
}
func main() {	router := http.NewServeMux()	router.HandleFunc("/", (func(w http.ResponseWriter, r *http.Request) {	json.NewEncoder(w).Encode(&ApiResponse{Code: http.StatusOK, Message: "Hello Wordl"})	}))	err := http.ListenAndServe(":3000", router)	if err != nil {	log.Fatal(err)	}
}

Source : | Last Update : Mon, 18 Apr 22

Question : golang http server

Answered by : restu-wahyu-saputra

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { data := map[string]string{"name": "john doe"} json.NewEncoder(w).Encode(data)
})
http.ListenAndServe(":3000", nil)

Source : | Last Update : Sat, 16 Apr 22

Answers related to http server golang

Code Explorer Popular Question For Erlang