Go
Here is a basic code example for implementing the server side in Go. In this example, we will create a simple web server with the following functions.
GET / : Returns “Hello, World!”
GET /users : Returns a list of users in JSON format
POST /users : Adds a user (accepts JSON)
```go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 | package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
// User model
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
var users = []User{
{ID: 1, Name: "Alice"},
{ID: 2, Name: "Bob"},
}
// Handler: "/" → return Hello, World!
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
}
// Handler: "/users" (GET) → return user list
func getUsersHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
// Handler: "/users" (POST) → add a new user
func createUserHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
var newUser User
if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
newUser.ID = len(users) + 1
users = append(users, newUser)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newUser)
}
func main() {
http.HandleFunc("/", helloHandler)
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
getUsersHandler(w, r)
} else if r.Method == http.MethodPost {
createUserHandler(w, r)
} else {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
})
fmt.Println("🚀 Server is running at http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
|