Answers for "golang http example"

Go
2

Golang HTTP Server

// Code by Divyanshu Shekhar - https://divyanshushekhar.com/golang-http-server/

// Golang HTTP Server
package main

import (
	"fmt"
	"log"
	"net/http"
)

const (
	// Host name of the HTTP Server
	Host = "localhost"
	// Port of the HTTP Server
	Port = "8080"
)

func home(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This is a Simple HTTP Web Server!")
}

func main() {
	http.HandleFunc("/", home)
	err := http.ListenAndServe(Host+":"+Port, nil)
	if err != nil {
		log.Fatal("Error Starting the HTTP Server : ", err)
		return
	}

}
Posted by: Guest on January-12-2021
0

golang http example

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))
}
Posted by: Guest on October-06-2021

Browse Popular Code Answers by Language