Git Product home page Git Product logo

gowebapp's Introduction

Hi there ๐Ÿ‘‹

Thanks for visiting. I hope you were able to use these contributions to help solve a problem. Good information is invaluable and can save hours of frustration. If the code was helpful, please star it or drop a comment. Thanks!

A few repositories demonstrating different front-end frameworks:

Linkedin: josephspurrier

gowebapp's People

Contributors

diegobernardes avatar josephspurrier avatar smenchions avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gowebapp's Issues

How to remove any user session?

I'm wondering how can a moderator force ANY user to logout when needed?

I unserstand that logout is done like this:

`sess := session.Instance(r)
// If user is authenticated
if sess.Values["id"] != nil {
	session.Empty(sess)
	sess.AddFlash(view.Flash{"Goodbye!", view.FlashNotice})
	sess.Save(r, w)
}`

And the instance is obtained like this:

// Instance returns a new session, never returns an error
func Instance(r *http.Request) *sessions.Session {
	session, _ := Store.Get(r, Name)
	return session
}

But I could not figure out how to get a user's session.Instance by userID instead of r *http.Request?

enhancement: use Bolt instead of SQLite, MySQL, or MongoDB

While not typical, just using Bolt would make deployments have less dependencies and be simple
to install ... more self contained. The database is similar to Mongo but not as robust, of course.
I kind of started on it here ... it's just a thought, but I will probably end up with MySQL as that's commonly used and available. Ultimately, I would like to access data from ElasticSearch, but that still requires something to handle users, sessions, and other meta-data-like stuff.
Thanks for this project.

Error to use RenderSingle with file in child folder?

I want to render single file but get this error:

Template Parse Error: open admin/test.html: no such file or directory

v := view.New(r)
v.Name = "admin/test"
v.RenderSingle(w)

After moving test file upper one level, it works.
Why?

How's about the backend - admin part?

I see you put all the routes on the same route file.
Hows about the backend and admin?.
Keeping all backend and frontend in the same binary file will causes the performance?

Since user have to load backend (route, template, shared variables, logic code ...) while using frontend?
In the runtime, all the template will be cached (allocate memory) included templates, logic code, variables, right?

Too many open files

I'm using gowebapp on a quite busy website along with redis for caching and MySQL as backend. But I get lots of too many open files in syslog which eventually causes the website to crash:

Feb 16 14:53:12 theuser gowebapp[23331]: server.go:3090: http: Accept error: accept tcp [::]:8080: accept4: too many open files; retrying in 10ms
Feb 16 14:53:12 theuser gowebapp[23331]: server.go:3090: http: Accept error: accept tcp [::]:8080: accept4: too many open files; retrying in 20ms
Feb 16 14:53:12 theuser gowebapp[23331]: server.go:3090: http: Accept error: accept tcp [::]:8080: accept4: too many open files; retrying in 40ms
Feb 16 14:53:12 theuser gowebapp[23331]: server.go:3090: http: Accept error: accept tcp [::]:8080: accept4: too many open files; retrying in 80ms
Feb 16 14:53:12 theuser gowebapp[23331]: server.go:3090: http: Accept error: accept tcp [::]:8080: accept4: too many open files; retrying in 5ms

To limit limit the http timeout I've add http.DefaultClient.Timeout = time.Minute * 2 to func routes() *httprouter.Router

func routes() *httprouter.Router {
        http.DefaultClient.Timeout = time.Minute * 2

        r := httprouter.New()

I have also increased Linux open file limits ulimit -n to over 100K.

But it did not fix the issue.

So appreciate your thoughts on how to fix this?

How to make a template function to add values

Hello Joseph,

In order to enumerate over a range of titles to start from 1 instead of 0 , I need an add template helper function, so that it can be used like this:

{{range $i , $a := .titles}}
   {{add $i 1}}. {{$a.Title}}
{{end}}

So I made this in add.go inside plugin folder:

package plugin

import (
	"html/template"
)

func Add() template.FuncMap {
	f := make(template.FuncMap)
	f["add"] = func(x, y int) int {
		return (x + y)
	}
	return f
}

But on runtime I get:

Template Parse Error: template: frontpage.tmpl:51: function "add" not defined

How can I fix this?

Thanks

Mysql database connect Problem

error log:
database.go:83: No connection could be made because the target machine actively refused it. 2016-03-31 06:08:08 PM Running HTTP :80
database.go:88: Database Error dial tcp 127.0.0.1:3306: connectex: No connection could be made because the target machine actively refused it.

enhancement: decorator-like func for controller actions

Just thought it might be useful in larger web apps that allow only authenticated users for most actions and pages to have a LoginRequired func somewhere in the package controller like:

func LoginRequired(w http.ResponseWriter, r *http.Request) *sessions.Session {
    // kind of like a decorator for controller actions
    // similar to rails controller "before_action :authenticate_user!"
    session := session.Instance(r)
    if session.Values["id"] == nil {
        // user has not logged in, so redirect to login page:
        http.Redirect(w, r, "/login", http.StatusFound)
        return session
    }
    return session
}

func Index(w http.ResponseWriter, r *http.Request) {
    session := LoginRequired(w, r)
    v := view.New(r)
    v.Name = "home/index"
    v.Vars["name"] = session.Values["name"]
    v.Render(w)
    // the previous code which is often repeated in controller actions:
    // session := session.Instance(r)
    // if session.Values["id"] != nil {
    //  v := view.New(r)
    //  v.Name = "home/index"
    //  v.Vars["name"] = session.Values["name"]
    //  v.Render(w)
    // } else {
    //  http.Redirect(w, r, "/login", http.StatusFound)
    //  return
    // }
}

... this would be much DRY-er code wise.
See: nsmsearch
Not really a proper decorator like here but it works.
Thoughts?

vendor folder conflicting with package manager

Hello. I see that the vendor folder is used as a folder containing all the code behind of the application... unfortunately, package managers (like dep) use this folder for storing external dependencies. This pretty much breaks everything... so it would be nice to move all the stuff in another location.

Sending CSRF token in jQuery POST?

Hello Joseph,
I'd like to let users to like posts through AJAX jQuery POST :

$(function(){
    $('#like').click(function(){
      function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
              }
            }
          }
          return cookieValue;
        }
        var token = getCookie('gosess');
        $.ajax({
         url: "/post/like/",  
         type: "POST",         
         beforeSend: function(xhr){xhr.setRequestHeader('token', token  );}, 
         data: { post_id: $(this).attr('name') },
         success: likeSuccess,
         error: likeError,
         dataType: 'html'
       });   
      });
  });

But the snippet above does returns null as cookie, presumably as the cookie is http only. Hence I get 403 error from gowebapp.

What is your suggestion to fix this?

Embed Files in Go 1.16

How to embed template and static folder using this app's templating system and view?

Many thanks

two submit forms in one page

Hello,
I am trying to use two submit forms on one page. It is working fine for one form but for second form I am getting this msg "Your token has expired". Can you help me get this resolve?

How to render html text?

Hello Joseph,
I'd like to render html formatted data so that when user posts something like <strong>My important task</strong> as content, it is rendered as bold text in the template.

How can I achieve this?

I tried using NOESCAPE in the template but it does not work.

Thanks

recaptcha v3 not supported

Hello Joeph,
The package does not work with recaptcha v.3

I get this error.

ERROR for site owner: Invalid key type

recaptcha v.2 is alright though.

How can I fix this?

Call parameter in config.json from middleware/controller

Hi Joseph,
I have a middleware containing this line of code

a := gormadapter.NewAdapter("mysql", "testuser:testpass@tcp(127.0.0.1:3306)/gowebapp", true) // Your driver and data source.

How can I replace this hardcoded connection string to use config in config.json

		"MySQL": {
			"Username": "testuser",
			"Password": "testpass",
			"Name": "gowebapp",
			"Hostname": "127.0.0.1",
			"Port": 3306,

Thanks

Your token expired, click here to try again.

Hello, Joseph,

I'm trying to make a file upload form, but get this annoying error and hope you can help to resolve it:

Your token expired, click here to try again.

And when I try again, I still get the same error.

routes:

	r.GET("/upload/photo/", hr.Handler(alice.
		New(acl.DisallowAnon).
		ThenFunc(controller.UploadPhotoGET)))

	r.POST("/upload/photo/", hr.Handler(alice.
		New(acl.DisallowAnon).
		ThenFunc(controller.UploadPhotoPOST)))

controllers:

func UploadPhotoGET(w http.ResponseWriter, r *http.Request) {

	sess := session.Instance(r)

	// Display the view
	v := view.New(r)
	v.Name = "article/upload"
	v.Vars["token"] = csrfbanana.Token(w, r, sess)
	v.Render(w)

}

func UploadPhotoPOST(w http.ResponseWriter, r *http.Request) {

//handle photo upload
var filename string
file, header, err := r.FormFile("uploadfile")

if err != nil {
	log.Println(err)
}
if header.Filename == "" {
	fmt.Println("\n\n NO file uploaded")

} else {
	data, err := ioutil.ReadAll(file)
	if err != nil {
		io.WriteString(w, err.Error())
		return
	}
	filename = path.Join("static/pics" + utils.RandString(5) + path.Ext(header.Filename))
	err = ioutil.WriteFile(filename, data, 0777)
	if err != nil {
		io.WriteString(w, err.Error())
		return
	}
	//resize photo
	filetoopen := filename
	img, err := imaging.Open(filetoopen)
	if err != nil {
		panic(err)
	}
	picname := filename
	thumbnail := imaging.Resize(img, 620, 0, imaging.Lanczos)
	// save cropped image
	err = imaging.Save(thumbnail, picname)
	if err != nil {
		fmt.Println(err)
	}
}

// Display the view
v := view.New(r)
v.Name = "article/upload"
v.Vars["message"] = "message"
v.Vars["url"] = filename
v.Render(w)

}

template:

{{define "title"}}Upload Photo{{end}}
{{define "head"}}{{end}}


{{define "content"}}
<div>
	<div>
		<h3>Add Photo</h3>
	</div>

	    {{if .prompt}}
             {{.prompt}} 
         {{end}}

         <br>

	    {{if .url}}
           {{.url}} 
         {{end}}

	 
			<form action="/upload/photo/" id="form" method="post" enctype="multipart/form-data">
		  			<input  type="file" name="uploadfile" />
					<br>
                  	<a title="Save" onclick="document.getElementById('form').submit();">					 Submit
				</a>
			</form> 
	 
</div>


{{end}}
{{define "foot"}}{{end}}

I tried to removing acl.DisallowAnon middleware from the routes, but it had no effect.

I don't get the error when I submit other forms:

It may worth mentioning that I invoke /upload/photo from within a form update page, from a toolbar icon:

			                    <a href="/upload/photo/" target="_blank">
			                        <span class="fa fa-picture-o fa-lg"></span>
			                    </a>

This bugs me for many hours. Really appreciate your hints.

How to build secretkey

Thank you very much for your project. I am a beginner. For the generation of secret keys, it is defined in the json file. How to generate secretkey

How to insert sub-templates?

Hello Joseph,
This may sound stupid question , but I was unable to insert an iconbar sub-template into my content template. What I want to achieve is that each article on the page (content area) has an iconbar snippet below it like this:

{{define "content"}}    
     {{range $n := .articles}}
         {{$n.Name}}        
         {{template "iconbar" .}} 
     {{end}}
{{end}}

I defined iconbar.tmpl inside /template/partial folder, and inserted {{template "iconbar" .}}, but at runtime I get:

Template File Error: html/template:articles.tmpl:56:14: no such template "iconbar".

I also tried other tricks to insert iconbar in base.tmpl but all failed.

So I'm clueless and appreciate your help.
Thanks in advance.

closed?

Sorry Joseph, this turned out to be a jQuery problem. Please delete.

Appear jsonconfig:20

i can not running your gowebapp,when i run in cmd is appear : " jsonconfig.go:20: open config\config.json: The system cannot find the path specified.
exit status 1" can you solve this problem.i hope you help me.thank you @josephspurrier

Sample CRUD

Hello Joseph,

I'm having difficulty to add a crud to the MVC. That would be great if you could add a sample post crud example.
Thanks

How to create global variable?

Hello Joseph,
I'm wondering what is the best way to create some global variables which are available to all packages?

register.go:89: Database is unavailable.

Hi Joseph,
I am trying to make a new gowebapp using mariadb 10 and go1.9.2 , but I get this error at registration:

$ go build && ./myapp 
2018-01-22 08:05:42 AM Running HTTP :8090
2018-01-22 08:05:47 AM 127.0.0.1:50590 POST /register
2018-01-22 08:05:48 AM 127.0.0.1:50590 GET /register
2018-01-22 08:05:49 AM 127.0.0.1:50590 GET /static/favicons/favicon-32x32.png
2018-01-22 08:05:57 AM 127.0.0.1:50590 POST /register
register.go:89: Database is unavailable.

Here is the relevant config.js:

	"Database": {
		"Type": "MySQL",
		"Bolt": {		
 			"Path": "gowebapp.db"
  		},
		"MongoDB": {
			"URL": "127.0.0.1",
			"Database": "myappdb"
		},
		"MySQL": {
			"Username": "myuser",
			"Password": "mypasswd",
			"Name": "myappdb",
			"Hostname": "127.0.0.1",
			"Port": 3306,
			"Parameter": "?parseTime=true"
		} 

I did not forget to replace the database name into myappdb before importing mysql.sql schema to mariadb.
In terminal, I can also connect to the database using myuser and mypassword and see 3 tables are being created on myappdb.

I have also another app based on gowebapp (created about a year a go) which is still compiles and runs fine.
So I'm out of ideas and appreciate your hints.

Can't use go get github.com/josephspurrier/gowebapp

Error Saying

Unrecognized import path "app/route" (gowebapp.go:9:2)
Unrecognized import path "app/shared/email" (gowebapp.go:11:2)
Unrecognized import path "app/shared/recaptcha" (gowebapp.go:13:2)
Unrecognized import path "app/shared/session" (gowebapp.go:15:2)
Unrecognized import path "app/shared/view" (gowebapp.go:16:2)
Unrecognized import path "app/shared/database" (gowebapp.go:10:2)
Unrecognized import path "app/shared/jsonconfig" (gowebapp.go:12:2)
Unrecognized import path "app/shared/server" (gowebapp.go:14:2)
Unrecognized import path "app/shared/view/plugin" (gowebapp.go:17:2)

Can not connect to mongodb

On an ubuntu machine, I have modified config.js to

"Database": {
        "Type": "MongoDB",
        "Bolt": {       
            "Path": "gowebapp.db"
        },
        "MongoDB": {
            "URL": "127.0.0.1",
            "Database": "gowebappdb"
        },

And I have created gowebappdb. However I get this error at compile time:

database.go:98: MongoDB Driver Error write tcp 127.0.0.1:34161->127.0.0.1:27017: i/o timeout
register.go:88: Database is unavailable.

Appreciate your hints.

server.go:2161: http: multiple response.WriteHeader calls

Hi there,

Really appreciate your work. I'm getting weird errors like "server.go:2161: http: multiple response.WriteHeader calls" in my error log after normal looking GET requests to the index page. It's a been a bit hard to debug and replicate.

I know this may be outside the purview of the project, but if you have any pointers on where I can look to track this down, that would be really helpful.

Thanks!

How to use redis as session backend?

Hi Joseph,
I'd like to use redis as session storage backend in order to bust the performance of my gowebapp but could not figure out how to apply the instructions found at [redistore](https://github.com/boj/redistore) into existing session.go code.

When I modify session.go like this:

package session

package session

import (
    "net/http"

    "github.com/gorilla/sessions"
    redisStore "gopkg.in/boj/redistore.v1"
)


 
var store *redisStore.RediStore
 var Name string
var err error

store, err = redisStore.NewRediStore(10, "tcp", ":6379", "", []byte("secret-key"))
if err != nil  {
  log.Fatal("error getting redis store : ", err)
}
defer store.Close()
 
type Session struct {
    Options   sessions.Options `json:"Options"`   
    Name      string           `json:"Name"`      
    SecretKey string           `json:"SecretKey"` 
}

 
func Configure(s Session) {
    Store := store
    Store.Options = &s.Options
    Name = s.Name
}

 func Instance(r *http.Request) *sessions.Session {
	session, _ := Store.Get(r, Name)
	return session
}

func Empty(sess *sessions.Session) {
	for k := range sess.Values {
		delete(sess.Values, k)
	}
}

But it does not work I get this error

syntax error: non-declaration statement outside function body

Really appreciate if you help me to fix this.

How to add pagination?

Hi Jojeph,

Will you please explain how to add pagination to gowebapp?
Regarding that Pagination is almost indispensable for a real world app, that would be great if you add it to the core features.

Thanks in advance.

initial

could not start the repository working

How to write the received note in a json file?

Hi @josephspurrier

I run this project and get a note which stored in a boltdb. Now I want to write that note in a json file instead of storing in a DB. How can I do that?

Where I can place this snippet code for do that?

// Where is the data? 
buf, err := json.Marshal(data)
if err !=nil {
    panic(err)
}

err = ioutil.WriteFile("fileame.json", buf, 0644)
if err !=nil {
    panic(err)
}

Any help would be greatly appreciated.

How to user both MySQL and BoltDB?

Hello Joseph,

I'd like to use MySQL for main database and BoltDB for caching but the config allows only one db.

I appreciate if you give instructions on how to use both?

How to split route into several files?

func routes() gets large and messy soon. I'm wondering how can I split it into several files, ech representing a particular entity?
What I want is something like:

func routes() *httprouter.Router {
	r := httprouter.New()
	r.NotFound = alice.
		New().
		ThenFunc(controller.Error404)

        notesRoutes()
        articlesRoutes()
        userRoutes()
       
     
	return r
}

How to add go mod to the project?

I'd like to add go modules to use versioning in my new project as some 3rd party packages don't work without mod anymore.
But after runing go mod init , can no longer build and get errrors like this:

go: creating new go.mod: module fancyweb
me@pc5:~/go/src/fancyweb$ go build && ./fancyweb 
vendor/app/shared/database/database.go:8:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/boltdb/bolt
vendor/app/controller/article-create.go:18:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/disintegration/imaging
vendor/app/shared/redis/pool.go:9:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/garyburd/redigo/redis
vendor/app/shared/database/database.go:9:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/go-sql-driver/mysql
vendor/app/shared/redis/util.go:8:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/gomodule/redigo/redis 
vendor/app/shared/session/session.go:6:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/gorilla/sessions
vendor/app/shared/recaptcha/recaptcha.go:7:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/haisum/recaptcha
vendor/app/shared/database/database.go:10:2: cannot find package "." in:
        /home/me/go/src/fancyweb/vendor/github.com/jmoiron/sqlx

How can I fix it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.