I’m working on an API which is something like
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func helloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", helloWorld).Methods("GET")
myRouter.HandleFunc("/", AllUsers).Methods("GET")
myRouter.HandleFunc("/user/{name}/{age}", NewUser).Methods("POST")
log.Fatal(http.ListenAndServe(":8081", myRouter))
}
func main() {
fmt.Println("GO orm tut")
InitialMigration()
handleRequests()
}
And here is my user.go file
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var db *gorm.DB
var err error
type User struct {
gorm.Model
Name string
Email string
}
func InitialMigration() {
db, err = gorm.Open("postgres", "dbname=users sslmode=disable")
if err != nil {
fmt.Println(err.Error())
panic("Failed to connect to database")
}
defer db.Close()
db.AutoMigrate(&User{})
}
func AllUsers(w http.ResponseWriter, r *http.Request) {
db, err = gorm.Open("postgres", "users")
if err != nil {
panic("Could not connect to database")
}
defer db.Close()
var users []User
db.Find(&users)
json.NewEncoder(w).Encode(users)
}
func NewUser(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "User")
}
But when I try a get request http://localhost:8081/users it doesn’t give anything. In postman it’s giving 404.
Can anyone help me with this?