Software of Development with Golang and MySQL

CRUD REST API GOLANG GORM AND MYSQL

Description

This repository is a Software of Application with Golang, Mux, GORM (ORM) and MySQL.

Installation

Using Go 1.16 preferably.

DataBase

Using MySQL preferably.

!EYE Configure DB info through the create of file .env

Apps

Using Postman, Insomnia, Talend API Tester, etc.

Usage

$ git clone https://github.com/DanielArturoAlejoAlvarez/CRUD-REST-API-WITH-GOLANG-1.16-3-GORM-AND-MYSQL.git
[NAME APP]

$ go build

$ ./[name-app] [ENTER]

Follow the following steps and you're good to go! Important:

alt text

Coding

Config

...
var DB *gorm.DB

var err error

var DNS = "root:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"

func InitialMigration() {
	DB, err = gorm.Open(mysql.Open(DNS), &gorm.Config{})
	if err != nil {
		fmt.Println(err.Error())
		panic("Can't connect to DB!")
	}

	DB.AutoMigrate(&User{})
}
...

Routes

...
func initializeRouter() {
	r := mux.NewRouter()

	r.HandleFunc("api/users", GetUsers).Methods("GET")
	r.HandleFunc("api/users/{id}", GetUser).Methods("GET")
	r.HandleFunc("api/users", CreateUser).Methods("POST")
	r.HandleFunc("api/users/{id}", UpdateUser).Methods("PUT")
	r.HandleFunc("api/users/{id}", DeleteUser).Methods("DELETE")

	log.Fatal(http.ListenAndServe(":9000",
		handlers.CORS(handlers.AllowedHeaders([]string{
			"X-Requested-With",
			"Content-Type",
			"Authorization"}),
			handlers.AllowedMethods([]string{
				"GET",
				"POST",
				"PUT",
				"DELETE",
				"HEAD",
				"OPTIONS"}),
			handlers.AllowedOrigins([]string{"*"}))(r)))
}
...

Controllers

...
func GetUsers(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var users []User
	DB.Find(&users)
	json.NewEncoder(w).Encode(users)
}

func GetUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	var user User
	DB.First(&user, params["id"])
	json.NewEncoder(w).Encode(user)
}

func CreateUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var user User
	json.NewDecoder(r.Body).Decode(&user)
	DB.Create(&user)
	json.NewEncoder(w).Encode(user)
}

func UpdateUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	var user User
	DB.First(&user, params["id"])
	json.NewDecoder(r.Body).Decode(&user)
	DB.Save(&user)
	json.NewEncoder(w).Encode(user)
}

func DeleteUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	var user User
	DB.Delete(&user, params["id"])
	json.NewEncoder(w).Encode(user)
}
...

Models

...
type User struct {
	gorm.Model
	DisplayName string `json:"displayname"`
	Email       string `json:"email"`
	Username    string `json:"username"`
	Phone       string `json:"phone"`
	Address     string `json:"address"`
	Age         int    `json:"age"`
	Avatar      string `json:"avatar"`
	Flag        bool   `json:"flag"`
}
...

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/DanielArturoAlejoAlvarez/CRUD-REST-API-WITH-GOLANG-1.16-3-GORM-AND-MYSQL. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Similar Resources

ging is a tool for create gin web framework development templates

ging ging is a tool for create gin web framework development templates This tool is for the freshmen who want to learn golang and gin web framework, i

Jan 15, 2022

Gorilla is a REST API template for efficient personal development, implemented based on the CleanArchitecture design philosophy.

Gorilla is a REST API template for efficient personal development, implemented based on the CleanArchitecture design philosophy.

The Gorilla Template is a REST API template for efficient personal development, implemented based on the CleanArchitecture design philosophy.

Feb 13, 2022

A Golang REST API to handle users and posts for a simple instagram backend. Uses MongoDB as the database. Tested using golang-testing and Postman.

A Golang REST API to handle users and posts for a simple instagram backend. Uses MongoDB as the database. Tested using golang-testing and Postman.

A Golang REST API to handle users and posts for a simple instagram backend. Uses MongoDB as the database. Tested using golang-testing and Postman.

Oct 10, 2021

A web forum built in Golang and SQLite and designed in SCSS

A web forum built in Golang and SQLite and designed in SCSS

Forum "Fairfax" 👉 What is it? A web forum built in Golang and SQLite and designed in SCSS. Members of the forum can take a personality test and be so

Nov 10, 2021

Go (Golang) API REST with Gin FrameworkGo (Golang) API REST with Gin Framework

go-rest-api-aml-service Go (Golang) API REST with Gin Framework 1. Project Description Build REST APIs to support AML service with the support of exte

Nov 21, 2021

[爬虫框架 (golang)] An awesome Go concurrent Crawler(spider) framework. The crawler is flexible and modular. It can be expanded to an Individualized crawler easily or you can use the default crawl components only.

go_spider A crawler of vertical communities achieved by GOLANG. Latest stable Release: Version 1.2 (Sep 23, 2014). QQ群号:337344607 Features Concurrent

Dec 30, 2022

A URL shortener using http://is.gd/ and the Go programming language (http://golang.org/)

goisgd A simple command line URL shortener using http://is.gd/. Getting the Code go get github.com/NickPresta/GoURLShortener Usage Import this librar

Apr 6, 2022

Extensible wiki system using CouchDB and written in Golang

Extensible wiki system using CouchDB and written in Golang

Wikifeat Introduction Wikifeat is an open source collaboration platform built around the ever-popular Wiki concept. It is meant to be extensible and h

Aug 23, 2022

A golang framework helps gopher to build a data visualization and admin panel in ten minutes

A golang framework helps gopher to build a data visualization and admin panel in ten minutes

the missing golang data admin panel builder tool. Documentation | 中文介绍 | DEMO | 中文DEMO | Twitter | Forum Inspired by laravel-admin Preface GoAdmin is

Dec 30, 2022
Simple Todolist using Golang IO and Mysql

Simple Todolist using Golang IO and Mysql HOW TO USE create 2 database with name : todolist for product todolist_test for test create table in both da

Nov 22, 2021
Give developers an easy way to create and integrate bank processing into their own software products
Give developers an easy way to create and integrate bank processing into their own software products

Community · Blog moov-io/bankcron Moov's mission is to give developers an easy way to create and integrate bank processing into their own software pro

Sep 27, 2022
Golang : Use gorm with mysql in gin

Golang : Use gorm with mysql in gin This repository guides to how ORM can be implemented in Golang. After cloning the code, follow below steps to let

Dec 9, 2021
Golang Gin Framework CRUD RestAPI with MySQL for music records.

web-service-gin Golang Gin Framework CRUD RestAPI with MySQL for music records. Installation This application runs on Go version 1.18.1. You can insta

Oct 17, 2022
Our collaborative Wiki software.

Emvi Wiki Support? No. This used to be our SaaS on emvi.com, but didn't work out the way we wanted. It's now open-source to help some of our users kee

Mar 4, 2022
A barebones URL Shortener implementation in Go using Gin and MySQL. Also features a basic frontend.

URL Shortener in Go This is a barebones URL Shortener implementation in Go using the Gin web framework and MySQL. Also features a basic frontend. Loca

Dec 22, 2021
Go-restapi - Go REST API with mysql and docker

GET localhost:8080/polygons localhost:8080/polygons/:name localhost:8080/polygon

Jan 24, 2022
ecommerce Go, Mysql, Redis, Selenium.

ecommerce Go, Mysql, Redis, Selenium. To run locally Have docker & docker-compose installed on your operating system. cp .env.example .env && docker-c

Aug 31, 2022
A ToDoList Demo based on Vue+Gin+Gorm+mysql
A ToDoList Demo based on Vue+Gin+Gorm+mysql

bubble清单 一个基于gin+gorm开发的练手小项目,通过该项目可初识go web开发该有的姿势。 前端页面基于vue和ElementUI开发,对前端不熟悉的童鞋可直接下载templates和static文件夹下的内容使用。 使用指南 下载 [email protected]:mao888/GoWe

Mar 16, 2022
Simple Todo List using Go & MySQL

Simple Todo List using Go & MySQL This is simple to-do list application, allowing user to manages and scheduling their to-do list. You can use your ow

Feb 9, 2022