ProductPromotion
Logo

Go.Lang

made by https://0x3d.site

How to create a simple REST API with Golang?

To create a simple REST API in Golang, use the net/http package to handle requests, define routes, and return JSON responses.

Building a simple REST API in Golang (Go) is a great way to understand how to work with web services. Go’s standard library provides robust support for HTTP, making it straightforward to create APIs. In this guide, we’ll walk through the steps required to create a simple REST API, covering routing, handling requests, and returning JSON responses.

1. Set Up Your Project

  • Start by creating a new directory for your project:
    mkdir go-rest-api
    cd go-rest-api
    
  • Initialize a new Go module:
    go mod init go-rest-api
    
  • Create a file named main.go.

2. Import Necessary Packages

  • Open main.go and import the required packages:
    package main
    import (
        "encoding/json"
        "net/http"
    )
    

3. Define a Data Structure

  • Define a struct that represents the data your API will handle. For instance, let’s create a simple User struct:
    type User struct {
        ID    int    `json:"id"`
        Name  string `json:"name"`
        Email string `json:"email"`
    }
    

4. Create a Sample Data Source

  • To simulate a database, create a slice of User structs:
    var users = []User{
        {ID: 1, Name: "John Doe", Email: "[email protected]"},
        {ID: 2, Name: "Jane Doe", Email: "[email protected]"},
    }
    

5. Set Up HTTP Handlers

  • Create a function to handle the /users endpoint, which returns the list of users as JSON:
    func getUsers(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(users)
    }
    
  • Register the handler in the main function:
    func main() {
        http.HandleFunc("/users", getUsers)
        http.ListenAndServe(":8080", nil)
    }
    

6. Testing Your API

  • To test your API, run the application:
    go run main.go
    
  • Open your browser or use a tool like Postman or curl to access http://localhost:8080/users. You should see the list of users returned as JSON:
    [
        {"id":1,"name":"John Doe","email":"[email protected]"},
        {"id":2,"name":"Jane Doe","email":"[email protected]"}
    ]
    

7. Handling Different HTTP Methods

  • You can expand your API by adding different handlers for different HTTP methods, such as POST, PUT, and DELETE. For example, to handle creating a new user:
    func createUser(w http.ResponseWriter, r *http.Request) {
        var newUser User
        if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        newUser.ID = len(users) + 1
        users = append(users, newUser)
        w.WriteHeader(http.StatusCreated)
        json.NewEncoder(w).Encode(newUser)
    }
    
  • Register this handler similarly using http.HandleFunc.

8. Conclusion Creating a REST API in Golang is a straightforward process thanks to its powerful standard library. You can expand this basic structure by adding more endpoints and functionality as needed, such as error handling, data validation, and connecting to a real database. With Go’s performance and simplicity, you can build robust APIs that serve your applications effectively.

Articles
to learn more about the golang concepts.

Resources
which are currently available to browse on.

mail [email protected] to add your project or resources here 🔥.

FAQ's
to know more about the topic.

mail [email protected] to add your project or resources here 🔥.

Queries
or most google FAQ's about GoLang.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory